package com.nimlib.utils;

import android.accounts.NetworkErrorException;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.jinlejia.erp.base.MapCallBack;
import com.netease.nimlib.sdk.RequestCallback;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import kotlin.random.Random;
import okhttp3.Call;
import okhttp3.MediaType;

class NimIMHttpClient {
    private Context context;
    private String appKey;
    private String appSecret;
    NimIMHttpClient(Context context){
        this.context = context;
        this.appKey = readMetaData(context,"com.netease.nim.appKey");
        this.appSecret = readMetaData(context,"com.netease.nim.appSecret");
    }

    //更新云信Token
    private final String RefreshToken = "https://api.netease.im/nimserver/user/refreshToken.action";
    //创建云信 账号
    private final String CreateID = "https://api.netease.im/nimserver/user/create.action";


    void httpLogin(Context context, String pin, boolean needToast,RequestCallback<NimLoginInfo> callback){
        refreshToken(pin, new IMTokenResult() {
            @Override
            public void success(String account, String token) {
                NimIMUtils.sdkLogin(context,account,token,callback);
            }

            @Override
            public void failed(String md5Pin, String msg) {
                createIM(pin, new IMTokenResult() {
                    @Override
                    public void success(String account, String token) {
                        NimIMUtils.sdkLogin(context,account,token,callback);
                    }

                    @Override
                    public void failed(String account, String msg) {
                        callback.onException(new NetworkErrorException(msg));
                        if (needToast)
                            CustomToast.showToast(NimIMHttpClient.this.context,msg,1500);
                    }
                });
            }
        });
    }

    private void refreshToken(String pin,IMTokenResult result){
        Map<String, String> headers = new HashMap<>();
        commonHeader(headers);
        commonHttp(RefreshToken, pin, result);
    }

    private void createIM(String pin,IMTokenResult result){
        Map<String, String> headers = new HashMap<>();
        commonHeader(headers);
        commonHttp(CreateID, pin, result);

    }

    private void commonHeader(Map<String, String> headers){
        //1.AppKey
        headers.put("AppKey",appKey);
        //2.Nonce
        String noce = String.valueOf(Random.Default.nextInt(10,200));
        headers.put("Nonce",noce);
        //3. CurTime
        java.util.TimeZone zone = java.util.TimeZone.getTimeZone("GMT-0:00");
        long second = Calendar.getInstance(zone).getTime().getTime();
        String curTime = String.valueOf(second);
        int curTimeLength = curTime.length();
        curTime = curTime.substring(0,curTimeLength-3);
        headers.put("CurTime",curTime);
        //4. CheckSum
        String checkSum = CheckSumBuilder.getCheckSum(appSecret,noce,curTime);
        headers.put("CheckSum",checkSum);
    }

    private void commonHttp(String url,String pin,IMTokenResult tokenResult){
        Map<String, String> headers = new HashMap<>();
        String account = NimIMUtils.imAccount(pin);
        commonHeader(headers);
        OkHttpUtils.postString().url(url)
                .content("accid="+account)
                .mediaType(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"))
                .headers(headers)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        tokenResult.failed(account,"网络连接失败，请稍后再试");
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        int code = Integer.parseInt(String.valueOf(response.get("code")))                                                                                                                                                                                     ;
                        if (code==200){
                            String info = String.valueOf(response.get("info"));
                            try{
                                String token = JSON.parseObject(info).getString("token");
                                tokenResult.success(account,token);
                            }catch (JSONException ignored){
                                tokenResult.failed(account,"聊天服务器连接失败，请稍后再试");
                            }
                        }else {
                            tokenResult.failed(account,"聊天服务器连接失败，请稍后再试");
                        }
                    }
                });
    }

    private interface IMTokenResult{
        void success(String account,String token);
        void failed(String account,String msg);
    }

    private String readMetaData(Context context,String key) {
        context = context.getApplicationContext();
        try {
            ApplicationInfo appInfo = context.
                    getPackageManager().
                    getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
